package uploadfile

import (
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/EDDYCJY/go-gin-example/pkg/logging"
	"gorm.io/gorm"
)

const default_temp_upload_file_path = "D:\\coding\\go\\go\\webserver\\temp"
const default_upload_file_path = "D:\\coding\\go\\go\\webserver\\uploads"

var db gorm.DB

func handleUploadFile(file io.Reader, fileName string, chunkIndex int) error {

	SaveChunkToFile(file, chunkIndex, "./temp", fileName)
	return nil
}

// SaveChunkToFile 将上传的分片保存到临时文件中
// 参数：
//   - src: 分片数据
//   - chunkIndex: 分片索引
//   - tempDir: 临时文件夹路径
//   - fileNmae: 临时文件名称
//
// 返回值：
//   - string: 临时文件路径
//   - error: 错误信息
func SaveChunkToFile(src io.Reader, chunkIndex int, tempDir string, fileName string) (string, error) {
	// 创建一个临时文件来保存分片
	err := os.MkdirAll(tempDir, os.ModePerm)
	if err != nil {
		return "", err
	}

	tempFilePath := filepath.Join(tempDir, fmt.Sprintf(fileName+"_%d", chunkIndex))
	tempFile, err := os.Create(tempFilePath)
	if err != nil {
		logging.Warn("创建临时文件失败: ", err.Error())
		return "", err
	}
	defer tempFile.Close()

	_, err = io.Copy(tempFile, src)
	if err != nil {
		logging.Warn("复制文件失败: ", err.Error())
		return "", err
	}

	return tempFilePath, nil
}
